package com.zxs.seckillweb.service.impl;

import com.zxs.constant.Constants;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Component
@Slf4j
public class LuaService {

    private DefaultRedisScript<Long> redisScript;
    //注意此处不要使用RedisTemplate，否则ARGV参数可能传不过去，是乱码
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PostConstruct
    public void init(){
        //设置lua脚本对象
        redisScript = new DefaultRedisScript<>();
        //设置返回类型
        redisScript.setResultType(Long.class);
        //读取lua脚本
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("seckill.lua")));
    }

    //运行lua脚本
    public Long runLuaScript(String orderId,String userId){
        //取当前时间戳  单位精确到秒
        String limitKey = System.currentTimeMillis() / 1000 + "";  //限流的key
        String holdKey = Constants.REDIS_HOLD + orderId + ":" + userId;  //该用户是否秒杀过该商品
        String storeKey = Constants.REDIS_STORE + orderId;  //商品库存的Key

        //把redis的key放到List里面
        List<String> keyList = Arrays.asList(limitKey, holdKey, storeKey);

        Long LuaExecuteResult = stringRedisTemplate.execute(redisScript, keyList, userId,String.valueOf(Constants.MAX_LIMIT));
        log.info("Lua脚本执行的结果{}", LuaExecuteResult);

        return LuaExecuteResult;
    }

}
